﻿//=====================================================
// Copyright © 2017-2018 xuxuzhaozhao
// All rights reserved
// GUID: e1d47e57-97ec-484c-8240-b259509df7e8
// CLR版本: 4.0.30319.42000
// 新建项输入的名称: ArticleService
// 机器名称: WIN10-20170502F
// 注册组织名: 成都名门汇科技有限公司（谊诚科技）
// 命名空间名称: UnitTestingWebAPI.Services
// 文件名: ArticleService
// 当前系统时间: 2017/10/21 17:32:16
// 当前登录用户名: xuxuzhaozhao
//======================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnitTestingWebAPI.Data.Infrstucture;
using UnitTestingWebAPI.Data.Repositories;
using UnitTestingWebAPI.Domain;

namespace UnitTestingWebAPI.Services
{
    // operations you want to expose
    public interface IArticleService
    {
        IEnumerable<Article> GetArticles(string name = null);
        Article GetArticle(int id);
        Article GetArticle(string name);
        void CreateArticle(Article article);
        void UpdateArticle(Article article);
        void DeleteArticle(Article article);
        void SaveArticle();
    }

    public class ArticleService : IArticleService
    {
        private readonly IArticleRepository _articlesRepository;
        private readonly IUnitOfWork _unitOfWork;

        public ArticleService(IArticleRepository articlesRepository, IUnitOfWork unitOfWork)
        {
            this._articlesRepository = articlesRepository;
            this._unitOfWork = unitOfWork;
        }

        #region IArticleService Members

        public IEnumerable<Article> GetArticles(string title = null)
        {
            if (string.IsNullOrEmpty(title))
                return _articlesRepository.GetAll();
            else
                return _articlesRepository.GetAll().Where(c => c.Title.ToLower().Contains(title.ToLower()));
        }

        public Article GetArticle(int id)
        {
            var article = _articlesRepository.GetById(id);
            return article;
        }

        public Article GetArticle(string title)
        {
            var article = _articlesRepository.GetArticleByTitle(title);
            return article;
        }

        public void CreateArticle(Article article)
        {
            _articlesRepository.Add(article);
        }

        public void UpdateArticle(Article article)
        {
            _articlesRepository.Update(article);
        }

        public void DeleteArticle(Article article)
        {
            _articlesRepository.Delete(article);
        }

        public void SaveArticle()
        {
            _unitOfWork.Commit();
        }

        #endregion
    }
}
